/*
 * Copyright 2013 The Scripps Research Institute
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package edu.scripps.fl.entrez.internal;

import java.net.ProxySelector;

import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.impl.conn.ProxySelectorRoutePlanner;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;

public class HttpClientBaseSingleton implements HttpClientBase {

	private static HttpClientBaseSingleton instance;
	private HttpClient client;

	public static HttpClientBaseSingleton getInstance() {
		if (instance == null) {
			synchronized (HttpClientBaseSingleton.class) { // 1
				if (instance == null) {
					synchronized (HttpClientBaseSingleton.class) { // 3
						// inst = new Singleton(); //4
						instance = new HttpClientBaseSingleton();
					}
					// instance = inst; //5
				}
			}
		}
		return instance;
	}

	public HttpClientBaseSingleton() {
		PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
		cm.setMaxTotal(100);
		HttpParams params = new BasicHttpParams();
		// HTTP 1.0 opens a new TCP connection for each request. Therefore use 1.1
		params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
		DefaultHttpClient defaultHttpClient = new DefaultHttpClient(cm, params);
		// configure a proxy via the standard jvm system properties http.proxyHost, http.proxyPort etc
		defaultHttpClient.setRoutePlanner(new ProxySelectorRoutePlanner(defaultHttpClient.getConnectionManager().getSchemeRegistry(),
				ProxySelector.getDefault()));
		client = defaultHttpClient;
	}

	public HttpClient getHttpClient() {
		return client;
	}

	public void setHttpClient(HttpClient client) {
		this.client = client;
	}

	@Override
	public void finalize() {
		getHttpClient().getConnectionManager().shutdown();
	}
}